package com.itheima.reggie.common;

import com.itheima.reggie.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@RestControllerAdvice(annotations = {RestController.class})
@Slf4j
public class GlobalExeptionHandler {

    /**
     * 异常处理的方法,捕获添加唯一约束的重复添加相同数据的异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.error(e.getMessage());
        //Duplicate entry 'admin' for key 'idx_username'
        if(e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * 异常处理的方法,捕获自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public R<String> exceptionHandler(BusinessException e){
        log.error(e.getMessage());
        return R.error(e.getMessage());

    }
}
